package com.tl.sun.ui.dialog;

import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.utils.EmptyUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.tl.sun.AppContext;
import com.tl.sun.OkHeader;
import com.tl.sun.R;
import com.tl.sun.event.CollectEvent;
import com.tl.sun.helper.UIHelper;
import com.tl.sun.model.CollectEntity;
import com.tl.sun.model.base.BaseEntity;
import com.tl.sun.ui.adapter.CollectAdapter;
import com.tl.sun.utils.ToastUtil;
import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.EventBus;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 作者：HQY on 17/8/9 14:58
 * 邮箱：hqy_xz@126.com
 */

public class CollectDialogFragment extends DialogFragment {

    @Bind(R.id.rl_model_collect_add)
    RelativeLayout mRlModelCollectAdd;
    @Bind(R.id.rv_model_collect)
    RecyclerView mRvModelCollect;
    @Bind(R.id.tv_dialog_edit)
    TextView mTvEdit;

    private List<CollectEntity> mCollectList = new ArrayList<>();
    private CollectAdapter mCollectAdapter;

    private String type;
    private boolean isHide = false;

    public static CollectDialogFragment newInstance(String type) {

        Bundle args = new Bundle();
        args.putString(UIHelper.TYPE, type);
        CollectDialogFragment fragment = new CollectDialogFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (EmptyUtils.isNotEmpty(getArguments())) {
            type = getArguments().getString(UIHelper.TYPE);
        }
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.Dialog_Tips);
        LayoutInflater inflater = getActivity().getLayoutInflater();
        View view = inflater.inflate(R.layout.dialog_collect_list, null);
        builder.setView(view);
        builder.setCancelable(false);
        ButterKnife.bind(this, view);
        initView();
        return builder.create();
    }

    private void initView() {
        if (type.equals("1")) {
            mRlModelCollectAdd.setVisibility(View.VISIBLE);
        } else {
            mRlModelCollectAdd.setVisibility(View.GONE);
        }

        mCollectAdapter = new CollectAdapter(mCollectList);
        mRvModelCollect.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRvModelCollect.setAdapter(mCollectAdapter);
        mRvModelCollect.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {

            }

            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                super.onItemClick(adapter, view, position);
                EventBus.getDefault().postSticky(new CollectEvent(mCollectList.get(position).getId(), type));
                dismiss();
            }

            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                super.onItemChildClick(adapter, view, position);
                switch (view.getId()) {
                    case R.id.rl_group_delete:
                        deleteGroup(mCollectList.get(position).getId() + "");
                        break;
                }
            }
        });
        mRlModelCollectAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                UIHelper.showAddEtDialog(getActivity(), "1","");
                dismiss();
            }
        });
        mTvEdit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isHide) {
                    isHide = false;
                    mTvEdit.setText("编辑");
                } else {
                    mTvEdit.setText("取消");
                    isHide = true;
                }
                for (int i = 0; i < mCollectList.size(); i++) {
                    mCollectList.get(i).setShow(isHide);
                }
                mCollectAdapter.notifyDataSetChanged();

            }
        });
        getCollectList();
    }

    /**
     * 获取收藏分组列表
     */
    private void getCollectList() {
        OkGo.getInstance().addCommonHeaders(OkHeader.getCommonHeadToken(getActivity()))
                .post(AppContext.getInstance().getBaseUrl() + "pond/group_list")
                .tag("collect")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        BaseEntity base = AppContext.getBaseEntity(s);
                        if (base.getRet() == 0) {
                            Gson gson = new Gson();
                            Type collectType = new TypeToken<BaseEntity<List<CollectEntity>>>() {
                            }.getType();
                            BaseEntity<List<CollectEntity>> collectList = gson.fromJson(s, collectType);
                            if (EmptyUtils.isNotEmpty(collectList.getData())) {
                                CollectEntity collect = new CollectEntity();
                                collect.setId(0);
                                collect.setName("默认分组");
                                mCollectList.add(collect);
                                mCollectList.addAll(collectList.getData());
                                if (type.equals("1")) {
                                    if (mCollectList.size() <= 5) {
                                        mRlModelCollectAdd.setVisibility(View.VISIBLE);
                                    } else {
                                        mRlModelCollectAdd.setVisibility(View.GONE);
                                    }
                                }
                                mCollectAdapter.setNewData(mCollectList);
                            } else {
                                CollectEntity collect = new CollectEntity();
                                collect.setId(0);
                                collect.setName("默认分组");
                                mCollectList.add(collect);
                                mCollectAdapter.setNewData(mCollectList);
                            }
                        } else {

                        }
                    }
                });
    }

    /**
     * 删除分组
     *
     * @param id
     */
    private void deleteGroup(String id) {
        OkGo.getInstance().addCommonHeaders(OkHeader.getCommonHeadToken(getActivity()))
                .post(AppContext.getInstance().getBaseUrl() + "pond/del_group")
                .tag("collect")
                .params("id", id)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        BaseEntity base = AppContext.getBaseEntity(s);
                        if (base.getRet() == 0) {
                            mTvEdit.setText("编辑");
                            isHide = false;
                            getCollectList();
                        } else {
                            ToastUtil.showToast(base.getMsg());
                        }
                    }
                });
    }

    @Override
    public void onStart() {
        super.onStart();
        Logger.e("收藏列表");
        Window window = getDialog().getWindow();
        WindowManager.LayoutParams wlp = window.getAttributes();
        wlp.gravity = Gravity.BOTTOM;
        wlp.width = WindowManager.LayoutParams.MATCH_PARENT;
        window.setAttributes(wlp);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        OkGo.getInstance().cancelTag("collect");
        ButterKnife.unbind(this);
    }


}
